<template>
  <div style="padding: 15px;">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" >
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item label="移位单">
              <el-input v-model="form.code" style="width:75%" disabled />
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item label="仓库">
              <el-select v-model="form.warehouseCode" placeholder="请选择" disabled>
                <el-option v-for="item in warehouseList" :key="item.value" :label="item.name" :value="item.code" />
              </el-select>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <div class="grid-content bg-purple">
            <el-form-item label="备注" prop="shipmentCode">
              <el-input v-model="form.remarks" style="width:75%" />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col >
          <el-button @click="chooseGoods">选择移位商品</el-button>
          <el-button :disabled="selectData.length === 0" @click="delGoods">删除</el-button>
        </el-col>
      </el-row>
    </el-form>
    <br>
    <vxe-table
      ref="xTable"
      border
      resizable
      stripe
      highlight-current-row
      align="center"
      show-footer
      keep-source
      highlight-hover-row
      :edit-rules="validRules"
      max-height="600"
      row-id="id"
      sort-config.remote
      class="mytable-footer"
      :loading="loading"
      auto-resize
      :data="tableData"
      :edit-config="{trigger: 'click', mode: 'cell'}"
      :checkbox-config="{ highlight: true, range: true}"
      @checkbox-all="selectChangeEvent"
      @checkbox-change="selectChangeEvent"
      @sort-change="sortList"
    >
      <vxe-table-column type="checkbox" width="60"></vxe-table-column>
      <vxe-table-column type="seq" width="60" title="序号"></vxe-table-column>
      <vxe-table-column :visible=false field="inventoryCode" min-width="200" title="库存标识" :formatter="formatInventoryCode" />
      <vxe-table-column title="入驻商" field="shipmentName" min-width="200" />
      <vxe-table-column field="goodsName" min-width="200" title="商品名称"  />
      <vxe-table-column field="goodsBarCode" title="商品条码" min-width="200"  />
      <vxe-table-column field="goodsUnitName" title="单位" min-width="80"  />
      <!-- <vxe-table-column field="num" title="数量" min-width="80"  /> -->
      <vxe-table-column field="spaceName" title="库区" min-width="200"  />
      <vxe-table-column field="locationName" title="移出库位" min-width="200"  />
      <!-- <vxe-table-column field="targetLocationName" title="移入库位" :edit-render="{name: 'ElSelect'}" width="270">
        <template v-slot:edit="{ row }">
          <locationElSelect  :val2="form.warehouseCode"  ref="locationElSelect" @setLocationCode="(data)=>{ setLocationCode(row, data) }" />
        </template>
      </vxe-table-column> -->
      <vxe-table-column field="moveQuantity" title="移出数量" min-width="200"  />
      <vxe-table-column field="gmtManufacture" title="生产日期" min-width="200"  />
      <vxe-table-column field="goodsStatusName" title="库存状态" min-width="200" />
      <vxe-table-column field="isLock" title="锁定状态" min-width="200" :formatter="formatIsLock"  />
      <vxe-table-column field="remarks" title="备注" min-width="200"  />
    </vxe-table>

    <vxe-toolbar/>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="funcSave" plain>保存</el-button>
      <el-button type="primary" @click="funcSubmit" plain>提交</el-button>
    </div>

    <vxe-modal v-model="modelChooseInventoryFlag" title="选择移位商品" width="1300" height="900" destroy-on-close>
      <moveChooseInventory :warehouseCode="form.warehouseCode" @fatherAddItem="fatherAddItem" />
    </vxe-modal>
  </div>
</template>
<script>
import Vue from "vue";
import "xe-utils";
import VXETable from "vxe-table";
import "vxe-table/lib/index.css";
import XEUtils from "xe-utils";
import VXEUtils from "vxe-utils";
import moveChooseInventory from './components/moveChooseInventory';
Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ["cookie"] });
import { moveAdd,moveDetail } from "@/api/store";
import { getWarehouse, getLocation } from "@/api/basicInfo";
import { isNumber } from '@/utils/validate.js'
import { moveItemList,moveUpdate } from "@/api/store";
  import locationElSelect from '@/views/components/locationElSelect.vue'

export default {
  name: "moveEdit",
  components: {
    moveChooseInventory,
    locationElSelect
  },
  data() {
    return {
      message: "",
      loading: false,
      tableData: [],
      locationData:[],

      code: "",
      itemListQuery: {
        //移位单号
        // moveCode: this.moveDetail.code,
        pageNum: 1,
        pageSize: 10,
        sortField: "",
        sortType: "",
      },

      warehouseList: [],
      locationList: [],

      modelChooseInventoryFlag: false,

      form: {
        code: '',
        warehouseCode: "",
        warehouseName: "",
        remarks: "",
        status: 0,
        moveItemVOList: [],
      },
        validRules: {
          moveQuantity: [
            { required: true, message: '数量必须填写' },
            { pattern: /^[1-9]+[0-9]*$/, message: '数量必须大于0' },
            { max: 20, message: '数量不能超过20位'}
          ],
        },

      rules:{
        warehouseCode: [
          { required: true, message: "请选择仓库", trigger: "blur" },
        ]
      },
      selectData: []
    };
  },
  created() {
    this.form.code = this.$route.query.code;
    this.selectWarehouseSpace()
    this.findWarehouseList();
    this.findLocationList();
    this.findMoveDetail();

  },
  methods: {
    // 选择仓库库区
    selectWarehouseSpace() {
      getLocation().then(response => {
        this.locationData = response.data
      });
    },

    setLocationCode(row, data){
      row.targetLocationName = data.value
      row.targetLocation = data.code
    },

    formatTotalQuantity({cellVal, row}){
      return row.num;
    },
    formatInventoryCode({cellVal, row}){
      return row.code;
    },
    formatIsLock({cellValue}){
      const isLockStaus = ['否', '是']
      return isLockStaus[cellValue]
    },

    getInfo(code) {
      this.form.code = code;
    },

    findWarehouseList(){
      getWarehouse().then((response)=>{
        this.warehouseList = response.data;
      })
    },

    findLocationList(){
      //const params = {'warehouseCode': this.form.warehouseCode}
      getLocation(this.form.warehouseCode).then((response)=>{
        const emptyItem = {'name':'--请选择--', 'code': ''};
        this.locationList.push(emptyItem);
        this.locationList = this.locationList.concat(response.data);
      })
    },

    // 获取移位单主表
    findMoveDetail() {
      const rLoading = this.openLoading({
        duration: 'infinity'
      })
      moveDetail(this.form.code).then((response) => {
        rLoading.close() // 关闭遮罩层
        this.form = response.data;
        this.tableData = this.form.moveItemVOList;
      });
    },

    // 选择库存
    chooseGoods(){
      if(this.form.warehouseCode == ""){
        this.$message.error('请选择仓库');
        return ;
      }
      this.modelChooseInventoryFlag = true;
    },


      // 添加明细
      fatherAddItem(data){
        if (data.length > 0) {
          data.forEach((item, idx) => {
            const result = this.tableData.filter(currentItem => currentItem.inventoryCode === item.code)
            if (result.length === 0) {
              this.tableData.push(item)
            } else {
              let idx = this.tableData.indexOf(result[0])
              Object.assign(this.tableData[idx], item)
            }
          })
          this.$refs.xTable.clearScroll()
        }
        this.modelChooseInventoryFlag = false;
      },
      // 删除
      delGoods() {
        this.$XModal.confirm('确定要删除所选数据吗？').then(type => {
          if (type === 'confirm') {
            this.selectData.forEach((item, idx) => {
                this.tableData.forEach((curItem, curIdx) => {
                  if(curItem.code === item.code) {
                    this.tableData.splice(curIdx, 1)
                  }
                })
            })
            setTimeout(()=>{
              this.selectData = []
            }, 100)
          }
        })
      },

    // 保存
    funcSave(){
      // 校验数据
      this.$refs.form.validate((valid) => {
        if (valid) {
          let datas = this.$refs.xTable.getTableData().tableData;
          if(datas.length == 0){
            this.$message.error('请添加移位明细');
            return;
          }
          // 计算总数
          let totalQuantity = 0;
          for(let data of datas){
            if(isNumber(data.moveQuantity)){
              totalQuantity += Number(data.moveQuantity);
            }
          }
          this.form.totalQuantity = totalQuantity;

          this.form.moveItemVOList = this.tableData;

          this.funcSaveOrSubmit();
        }
      });
    },

    // 提交
    funcSubmit(){
      // 校验数据
      this.$refs.form.validate((valid) => {
        if (valid) {
          let datas = this.$refs.xTable.getTableData().tableData;
          if(datas.length == 0){
            this.$message.error('请添加移位明细');
            return;
          }

          // 计算总数
          let totalQuantity = 0;
          const count = datas.length;
          console.info(1)
          for(let i =0; i<count; i++){
            // 判断移入库位、移入数量是否填写；
              //datas[i].targetLocation == undefined || datas[i].targetLocation  == '' ||
            //   if(!isNumber(datas[i].moveQuantity) || Number(datas[i].moveQuantity) <0 ){
            //     this.$message.error(`第${i+1}行没有填写移位数量信息`);
            //     return ;
            // }

            if(isNumber(datas[i].moveQuantity)){
              totalQuantity += Number(datas[i].moveQuantity);
            }
          }
          this.form.totalQuantity = totalQuantity;
          this.form.moveItemVOList = this.tableData;
          this.form.status = 11;

          this.funcSaveOrSubmit();

        }
      });
    },

    //
    funcSaveOrSubmit(){
      const params = this.form;
      const rLoading = this.openLoading({
        text: '处理中...',
        duration: 'infinity'
      })
      moveUpdate(params).then((response)=>{
        if(response.status == 0){
          this.$message({ message: '保存成功', type: 'success' });
          this.$eventBus.$emit('refreshList')
          this.$store.dispatch("tagsView/delView", this.$route);
          this.$router.push({ path: "move" })
        }else{
          this.$message.error(response.msg);
        }
      }).finally(()=>{
          rLoading.close() // 关闭遮罩层
        })
    },

    // 排序
    sortList({ column, property, order }) {
      if (order) {
        this.itemListQuery.sortField = property;
        this.itemListQuery.sortType = order;
      } else {
        this.listQuery.sortField = "";
      }
      this.findMoveDetail();
    },

    // 全选与否，勾选、取消事件
    selectChangeEvent({ checked, selection }) {
      this.selectData = selection
    },    // 分页handle
    handlePageChange({ currentPage, pageSize }) {
      this.itemListQuery.pageNum = currentPage;
      this.itemListQuery.pageSize = pageSize;
      this.findMoveDetail();
    },
    // 设置底部合计
    footerMethod({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return "合计";
          }
          if (["pageviews", "forecast"].includes(column.property)) {
            return XEUtils.sum(data, column.property);
          }
          return null;
        }),
      ];
    },





  },
};
</script>

<style>
.vxe-table .vxe-body--column:not(.col--ellipsis),
.vxe-table .vxe-footer--column:not(.col--ellipsis),
.vxe-table .vxe-header--column:not(.col--ellipsis) {
  padding: 6px 0;
}
.vxe-toolbar {
  padding: 0 0 10px 0;
}
</style>
<style lang="scss" scoped>
  .dialog-footer {
    margin: 35px auto;
    width: 175px;
    // float: right;
  }
</style>
